package com.jacky.demo.func;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jacky.demo.BaseActivity;
import com.jacky.demo.BuildConfig;
import com.jacky.demo.dialog.WebPopupMenu;
import com.jacky.demo.util.AppUtils;
import com.jacky.demo.util.StorageUtil;
import com.jacky.log.Logger;

import java.io.File;

/**
 * Created by Administrator on 2018-01-04.
 */

public class WebViewActivity extends BaseActivity {

    @Override
    protected int getContentView() {
        return 0;
    }

    @Override
    protected void initCreate() {}

    private static int FILE_CHOOSER_RESULT_CODE = 5058;
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private boolean multiple = false;

    WebView mView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("网页操作");

        mView = new WebView(this);
        initWebView();
        setContentView(mView);

        mView.loadUrl("file:///android_asset/web.html");
    }

    private void initWebView() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
        }
        WebSettings settings = mView.getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setUseWideViewPort(true);
//        settings.setUserAgentString(AppConfig.USER_AGENT);
        settings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setBuiltInZoomControls(true); // 设置显示缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setLoadWithOverviewMode(true);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
        }
        settings.setAllowContentAccess(true);
//        settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        // 设置缓存模式
        settings.setCacheMode(settings.LOAD_DEFAULT); // 设置缓存模式
        /*
         * 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：
         * 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
         */
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        /**
         * 这里需要根据不同的分辨率设置不同的比例,比如
         * 5寸手机设置190  屏幕宽度 > 650   180
         * 4.5寸手机设置170  屏幕宽度>  500 小于 650  160
         * 4寸手机设置150  屏幕宽度>  450 小于 550  150
         * 3           屏幕宽度>  300 小于 450  120
         * 小于    300  100
         *  320×480  480×800 540×960 720×1280
         */
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        if(width > 650) mView.setInitialScale(190);
        else if(width > 520) mView.setInitialScale(160);
        else if(width > 450) mView.setInitialScale(140);
        else if(width > 300) mView.setInitialScale(120);
        else mView.setInitialScale(100);

        mView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView webView, String title) {
                super.onReceivedTitle(webView, title);
//                if(TextUtils.isEmpty(mDefaultTitle)) {
//                    setTitle(title);
//                }
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }
            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                multiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE;
                openImageChooserActivity();
                return true;
            }

            private void openImageChooserActivity() {
                AppUtils.requestPermission(getActivity(), FILE_CHOOSER_RESULT_CODE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        });
        mView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView webView, String url) {
                super.onPageFinished(webView, url);
//                if(BuildConfig.SHOW_LOG) {
                    Logger.d("page finish url", url);
                    webView.loadUrl("javascript:window.console.log('<html>'+"
                            + "document.getElementsByTagName('html')[0].innerHTML+'</html>');");
//                }
            }
        });
        mView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult result = mView.getHitTestResult();
                if(result.getType() == WebView.HitTestResult.IMAGE_TYPE) {
                    String imgurl = result.getExtra();
                    WebPopupMenu.show(getActivity(), imgurl);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == FILE_CHOOSER_RESULT_CODE ) {
            if(AppUtils.isPermissionOK(getActivity(), permissions, grantResults)) {
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple);

                Intent chooser = createChooserIntent(createCameraIntent());
                chooser.putExtra(Intent.EXTRA_INTENT, i);
                startActivityForResult(chooser, FILE_CHOOSER_RESULT_CODE);
            } else {
                showToast("没有permission_read_storage权限");
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(null);
                    uploadMessageAboveL = null;
                }
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(resultCode, data);
            } else if (uploadMessage != null) {
                Uri result = null;
                if(resultCode == RESULT_OK) {
                    if(data == null) {
                        File file = new File(StorageUtil.getImageDir(), "camera.jpg");
                        if(file.exists()) {
                            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            result = AppUtils.fromFile(getActivity(), i, file);
                        }
                    } else {
                        result = data.getData();
                    }
                }
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int resultCode, Intent intent) {
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            } else {
                File file = new File(StorageUtil.getImageDir(), "camera.jpg");
                if(file.exists()) {
                    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri data = AppUtils.fromFile(getActivity(), i, file);
                    results = new Uri[]{data};
                }
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "选择操作");
        return chooser;
    }

    private Intent createCameraIntent() {
        File file = new File(StorageUtil.getImageDir(), "camera.jpg");
        if(file.exists()) file.delete();

        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri data = AppUtils.fromFile(getActivity(), i, file);
        i.putExtra(MediaStore.EXTRA_OUTPUT, data);
        return i;
    }
//            private Intent createCamcorderIntent() {
//                return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//            }
//
//            private Intent createSoundRecorderIntent() {
//                return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
//            }
}
